<template>
  <div class="meal-record-container">
    <el-row :gutter="20">
      <!-- 左侧记录表单 -->
      <el-col :xs="24" :sm="24" :md="10">
        <el-card class="meal-form-card">
          <template #header>
            <div class="card-header">
              <span>添加膳食记录</span>
              <el-button type="primary" @click="handleSubmit" :loading="loading">
                保存记录
              </el-button>
            </div>
          </template>

          <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="日期" prop="date">
              <el-date-picker
                v-model="form.date"
                type="date"
                placeholder="选择日期"
                :disabled-date="disabledDate"
                style="width: 100%"
              />
            </el-form-item>

            <el-form-item label="时间" prop="time">
              <el-time-picker
                v-model="form.time"
                format="HH:mm"
                placeholder="选择时间"
                style="width: 100%"
              />
            </el-form-item>

            <el-form-item label="餐次" prop="mealType">
              <el-radio-group v-model="form.mealType">
                <el-radio :value="'breakfast'">早餐</el-radio>
                <el-radio :value="'lunch'">午餐</el-radio>
                <el-radio :value="'dinner'">晚餐</el-radio>
                <el-radio :value="'snack'">加餐</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="食物" prop="foodId">
              <el-select
                v-model="form.foodId"
                filterable
                remote
                reserve-keyword
                placeholder="搜索食物"
                :remote-method="handleFoodSearch"
                :loading="foodSearchLoading"
                style="width: 100%"
              >
                <el-option
                  v-for="item in foodOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                  <div class="food-option">
                    <span>{{ item.name }}</span>
                    <small>{{ item.calories }}kcal/100g</small>
                  </div>
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="份量(g)" prop="amount">
              <el-input-number
                v-model="form.amount"
                :min="1"
                :max="1000"
                style="width: 100%"
              />
            </el-form-item>

            <el-form-item label="备注" prop="note">
              <el-input
                v-model="form.note"
                type="textarea"
                :rows="2"
                placeholder="添加备注信息"
              />
            </el-form-item>
          </el-form>

          <!-- 营养成分预览 -->
          <div v-if="selectedFood" class="nutrition-preview">
            <h4>营养成分预览 ({{ form.amount }}g)</h4>
            <el-row :gutter="20">
              <el-col :span="6" v-for="item in nutritionInfo" :key="item.label">
                <div class="nutrition-item">
                  <div class="value">{{ item.value }}</div>
                  <div class="label">{{ item.label }}</div>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧记录列表 -->
      <el-col :xs="24" :sm="24" :md="14">
        <el-card class="meal-list-card">
          <template #header>
            <div class="card-header">
              <div class="header-left">
                <span>膳食记录</span>
                <el-date-picker
                  v-model="currentDate"
                  type="date"
                  placeholder="选择日期"
                  :disabled-date="disabledDate"
                  @change="handleDateChange"
                  size="small"
                />
              </div>
              <div class="nutrition-summary" v-if="dailySummary">
                <span>今日摄入：</span>
                <el-tag size="small">热量 {{ dailySummary.calories }}kcal</el-tag>
                <el-tag size="small" type="success">蛋白质 {{ dailySummary.protein }}g</el-tag>
                <el-tag size="small" type="warning">碳水 {{ dailySummary.carbs }}g</el-tag>
                <el-tag size="small" type="danger">脂肪 {{ dailySummary.fat }}g</el-tag>
              </div>
            </div>
          </template>

          <el-timeline>
            <el-timeline-item
              v-for="record in dailyRecords"
              :key="record.id"
              :timestamp="record.time"
              :type="getTimelineItemType(record.mealType)"
            >
              <div class="meal-record-item">
                <div class="record-header">
                  <h4>{{ getMealTypeText(record.mealType) }}</h4>
                  <div class="actions">
                    <el-button
                      type="primary"
                      link
                      @click="handleEdit(record)"
                    >
                      编辑
                    </el-button>
                    <el-button
                      type="danger"
                      link
                      @click="handleDelete(record)"
                    >
                      删除
                    </el-button>
                  </div>
                </div>
                <p class="food-name">{{ record.foodName }} {{ record.amount }}g</p>
                <p v-if="record.note" class="note">备注：{{ record.note }}</p>
                <div class="nutrition-tags" v-if="record">
                  <el-tag v-if="record.calories" size="small">{{ record.calories }}kcal</el-tag>
                  <el-tag v-if="record.protein" size="small" type="success">蛋白质{{ record.protein }}g</el-tag>
                  <el-tag v-if="record.carbs" size="small" type="warning">碳水{{ record.carbs }}g</el-tag>
                  <el-tag v-if="record.fat" size="small" type="danger">脂肪{{ record.fat }}g</el-tag>
                </div>
              </div>
            </el-timeline-item>
          </el-timeline>

          <div v-if="!dailyRecords.length" class="empty-state">
            <el-empty description="暂无膳食记录" />
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useStore } from 'vuex'
import { ElMessage, ElMessageBox } from 'element-plus'
import { formatTime } from '@/utils/date'
import { searchFood } from '@/api/food'

const store = useStore()
const formRef = ref(null)
const loading = ref(false)
const foodSearchLoading = ref(false)
const currentDate = ref(new Date())
const foodOptions = ref([])
const userId = computed(() => store.getters['user/userId'])

// 表单数据
const form = reactive({
  date: new Date(),
  time: new Date(),
  mealType: '',
  foodId: '',
  amount: 100,
  note: ''
})

// 表单验证规则
const rules = {
  date: [{ required: true, message: '请选择日期', trigger: 'change' }],
  time: [{ required: true, message: '请选择时间', trigger: 'change' }],
  mealType: [{ required: true, message: '请选择餐次', trigger: 'change' }],
  foodId: [{ required: true, message: '请选择食物', trigger: 'change' }],
  amount: [{ required: true, message: '请输入份量', trigger: 'blur' }]
}

// 选中的食物信息
const selectedFood = computed(() => {
  return foodOptions.value.find(item => item.id === form.foodId)
})

// 营养成分预览
const nutritionInfo = computed(() => {
  if (!selectedFood.value) return []
  const ratio = form.amount / 100
  return [
    { label: '热量(kcal)', value: Math.round(selectedFood.value.calories * ratio) },
    { label: '蛋白质(g)', value: (selectedFood.value.protein * ratio).toFixed(1) },
    { label: '碳水(g)', value: (selectedFood.value.carbs * ratio).toFixed(1) },
    { label: '脂肪(g)', value: (selectedFood.value.fat * ratio).toFixed(1) }
  ]
})

// 每日记录和汇总
const dailyRecords = computed(() => {
  return store.state.meals.dailyMeals || []
})

const dailySummary = computed(() => {
  const summary = store.state.meals.nutritionSummary || {}
  return {
    calories: summary.calories || 0,
    protein: summary.protein || 0,
    carbs: summary.carbs || 0,
    fat: summary.fat || 0
  }
})

// 餐次类型映射
const mealTypeMap = {
  breakfast: { text: '早餐', type: 'primary' },
  lunch: { text: '午餐', type: 'success' },
  dinner: { text: '晚餐', type: 'warning' },
  snack: { text: '加餐', type: 'info' }
}

const getMealTypeText = (type) => mealTypeMap[type]?.text || type
const getTimelineItemType = (type) => mealTypeMap[type]?.type || 'primary'

// 日期限制
const disabledDate = (time) => {
  return time.getTime() > Date.now()
}

// 搜索食物
const handleFoodSearch = async (query) => {
  if (query) {
    try {
      foodSearchLoading.value = true
      const res = await searchFood(query)
      foodOptions.value = res.data
    } catch (error) {
      console.error('搜索食物失败:', error)
    } finally {
      foodSearchLoading.value = false
    }
  } else {
    foodOptions.value = []
  }
}

// 获取每日膳食记录
const fetchDailyMeals = async (date = form.date) => {
  if (!userId.value) return
  try {
    await store.dispatch('meals/getDailyMeals', {
      date
    })
  } catch (error) {
    ElMessage.error(error.message || '获取膳食记录失败')
  }
}

// 日期变更
const handleDateChange = (date) => {
  fetchDailyMeals(date)
}

// 重置表单
const resetForm = () => {
  form.mealType = ''
  form.foodId = ''
  form.amount = 100
  form.note = ''
  foodOptions.value = []
  // 重置后刷新记录
  fetchDailyMeals()
}

// 提交记录
const handleSubmit = () => {
  formRef.value.validate(async valid => {
    if (valid) {
      try {
        loading.value = true
        const data = {
          ...form,
          time: formatTime(form.time),
          userId: userId.value  // 添加 userId
        }
        await store.dispatch('meals/addMealRecord', data)
        ElMessage.success('记录添加成功')
        resetForm()
      } catch (error) {
        console.error('添加记录失败:', error)
        ElMessage.error(error.message || '添加记录失败')
      } finally {
        loading.value = false
      }
    }
  })
}

// 编辑记录
const handleEdit = (record) => {
  Object.assign(form, {
    ...record,
    date: new Date(record.date),
    time: new Date(`2000-01-01 ${record.time}`)
  })
}

// 删除记录
const handleDelete = (record) => {
  ElMessageBox.confirm('确定要删除这条记录吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await store.dispatch('meals/deleteMealRecord', {
        id: record.id,
        date: record.date,
        userId: userId.value  // 添加 userId
      })
      ElMessage.success('删除成功')
      fetchDailyMeals()  // 刷新记录
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error(error.message || '删除失败')
    }
  })
}

// 初始化
onMounted(() => {
  fetchDailyMeals(new Date())
})

// 监听用户ID变化
watch(userId, (newVal) => {
  if (newVal) {
    fetchDailyMeals()
  }
})
</script>

<style lang="scss" scoped>
.meal-record-container {
  padding: 20px;

  .meal-form-card {
    margin-bottom: 20px;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .nutrition-preview {
      margin-top: 20px;
      padding-top: 20px;
      border-top: 1px solid var(--el-border-color-lighter);

      h4 {
        margin: 0 0 16px;
        color: var(--el-text-color-primary);
      }

      .nutrition-item {
        text-align: center;
        
        .value {
          font-size: 18px;
          color: var(--el-color-primary);
          font-weight: bold;
        }
        
        .label {
          font-size: 12px;
          color: var(--el-text-color-secondary);
          margin-top: 4px;
        }
      }
    }
  }

  .meal-list-card {
    .card-header {
      .header-left {
        display: flex;
        align-items: center;
        gap: 16px;
      }

      .nutrition-summary {
        margin-top: 12px;
        
        .el-tag {
          margin-left: 8px;
        }
      }
    }

    .meal-record-item {
      .record-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 8px;

        h4 {
          margin: 0;
        }
      }

      .food-name {
        margin: 8px 0;
        color: var(--el-text-color-primary);
      }

      .note {
        margin: 8px 0;
        color: var(--el-text-color-secondary);
        font-size: 14px;
      }

      .nutrition-tags {
        margin-top: 8px;
        
        .el-tag {
          margin-right: 8px;
        }
      }
    }

    .empty-state {
      padding: 40px 0;
    }
  }
}

.food-option {
  display: flex;
  justify-content: space-between;
  align-items: center;

  small {
    color: var(--el-text-color-secondary);
  }
}
</style> 